package cn.cxq.learning.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 哈夫曼树
 * 实现思路：
 * 每次将最小的两个节点合并作为新节点的左右子节点，然后再将新的节点加入到集合中，移除集合中该节点的左右子节点
 */
public class HuffmanTree {

    private HuffmanNode root;

    public HuffmanTree(int[] arr) {

        List<HuffmanNode> huffmanNodeList = new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            HuffmanNode huffmanNode = new HuffmanNode(arr[i]);
            huffmanNodeList.add(huffmanNode);
        }

        while (huffmanNodeList.size()>1){

            Collections.sort(huffmanNodeList);

            HuffmanNode leftNode = huffmanNodeList.get(0);
            HuffmanNode rightNode = huffmanNodeList.get(1);

            HuffmanNode newNode = new HuffmanNode(leftNode.value + rightNode.value);

            newNode.left = leftNode;
            newNode.right = rightNode;

            huffmanNodeList.remove(leftNode);
            huffmanNodeList.remove(rightNode);
            huffmanNodeList.add(newNode);

        }

        this.root = huffmanNodeList.get(0);
    }

    public void preorderTransversal(){
        if (this.root==null) System.out.println("哈夫曼树为空~~~");
        else this.root.preorderTransversal();
    }
}

class HuffmanNode implements Comparable<HuffmanNode>{

    int value;
    HuffmanNode left;
    HuffmanNode right;

    public HuffmanNode(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "HuffmanNode{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(HuffmanNode huffmanNode) {
        return this.value - huffmanNode.value;
    }

    public void preorderTransversal(){

        System.out.println(this);

        if (this.left!= null) this.left.preorderTransversal();
        if (this.right!= null) this.right.preorderTransversal();
    }
}
